package cn.itlaobing.web.servlet;

import cn.itlaobing.dao.OrderDao;
import cn.itlaobing.exception.BusinessException;
import cn.itlaobing.model.OrderModel;
import cn.itlaobing.model.UserModel;
import cn.itlaobing.service.OrderService;
import cn.itlaobing.service.UserService;
import cn.itlaobing.service.impl.OrderServiceImpl;
import cn.itlaobing.service.impl.UserServiceImpl;
import cn.itlaobing.web.Constants;
import cn.itlaobing.web.annotation.RequestMapping;
import com.alibaba.druid.pool.vendor.SybaseExceptionSorter;
import com.alibaba.fastjson.JSON;
import jdk.nashorn.internal.ir.debug.JSONWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.io.IOException;
import java.io.SyncFailedException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/3.
 */
@WebServlet("/orders/*")
public class OrderServlet extends BaseServlet{
    @RequestMapping("/show")
    protected void show(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        OrderService os=new OrderServiceImpl();

        UserModel um= (UserModel) req.getSession().getAttribute("USER_IN_SESSIONSCOPE");
        List<OrderModel> list=null;

        try {
            list=os.show(um.getUserId());
        } catch (BusinessException e) {
            e.printStackTrace();
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
            return;
        }
            System.out.println(list.size()+">>>>>>>>>>>");
            req.getSession().setAttribute("ORDERLIST",list);
            req.getRequestDispatcher("/WEB-INF/views/order/show.jsp").forward(req,resp);
    }
    //如果订单是未支付，可以点击 “支付按钮”，直接更改订单状态为“正在配货”，
    // 也可点击”取消”按钮，直接更改订单状态为”已取消”
    @RequestMapping("/payment")
    public void update(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String orderId=request.getParameter("orderId");
        UserModel userModel= (UserModel) request.getSession().getAttribute("USER_IN_SESSIONSCOPE");
        OrderDao orderDao=new OrderDao();
        try {
            OrderModel orderModel=orderDao.payment(orderId);
            response.setContentType("application/json;charset=utf-8");
            if(orderModel==null){
                response.getWriter().write("");
                return;
            }
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("orderCode",orderModel.getOrderId());
            map.put("orderStatus",orderModel.getStatus().getText());
            response.getWriter().write(JSON.toJSONString(map));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
